#-*- codeing = utf-8 -*-
#@Time : 2020/9/13 16:18
#@Author : 阳某
#@File : 模拟12306登录.py
#@Software : PyCharm
import requests
from hashlib import md5
class Chaojiying_Client(object):
    def __init__(self, username, password, soft_id):
        self.username = username
        password =  password.encode('utf8')
        self.password = md5(password).hexdigest()
        self.soft_id = soft_id
        self.base_params = {
            'user': self.username,
            'pass2': self.password,
            'softid': self.soft_id,
        }
        self.headers = {
            'Connection': 'Keep-Alive',
            'User-Agent': 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0)',
        }
    def PostPic(self, im, codetype):
        """
        im: 图片字节
        codetype: 题目类型 参考 http://www.chaojiying.com/price.html
        """
        params = {
            'codetype': codetype,
        }
        params.update(self.base_params)
        files = {'userfile': ('ccc.jpg', im)}
        r = requests.post('http://upload.chaojiying.net/Upload/Processing.php', data=params, files=files, headers=self.headers)
        return r.json()
    def ReportError(self, im_id):
        """
        im_id:报错题目的图片ID
        """
        params = {
            'id': im_id,
        }
        params.update(self.base_params)
        r = requests.post('http://upload.chaojiying.net/Upload/ReportError.php', data=params, headers=self.headers)
        return r.json()
from selenium import webdriver
import time
from selenium.webdriver import ChromeOptions

# 关闭自动测试状态显示 // 会导致浏览器报：请停用开发者模式
# window.navigator.webdriver还是返回True,当返回undefined时应该才可行。
option = ChromeOptions()
option.add_experimental_option("excludeSwitches", ['enable-automation'])
# 如何实现让selenium规避被检测的风险
bro = webdriver.Chrome(options=option)
# 通过浏览器的dev_tool在get页面钱将.webdriver属性改为"undefined"
bro.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", {  # 直接滑块消失
    "source": """Object.defineProperty(navigator, 'webdriver', {get: () => undefined})""",
})

bro.maximize_window()       #窗口最大化
bro.get('https://kyfw.12306.cn/otn/resources/login.html')
time.sleep(2)
tran = bro.find_element_by_class_name('login-hd-account')
tran.click()
time.sleep(1)
bro.find_element_by_id('J-userName').send_keys('18296405761')
time.sleep(1)
bro.find_element_by_id('J-password').send_keys('yang521521')
time.sleep(1)
bro.save_screenshot('aa.png')       #保存页面屏幕截图
# 确定验证码图片左上角和右下角坐标（裁剪的区域就确定）
code_img_ele = bro.find_element_by_id('J-loginImg')
location = code_img_ele.location    #验证码图片左上角的坐标x，y
print('location:',location)
size = code_img_ele.size    #验证码标签对应的长和宽
print('size:',size)
# 左上角和右下角坐标
rangle = (
    int(location['x']),int(location['y']),int(location['x']+size['width']),int(location['y']+size['height'])
)
# 至此验证码图片区域就确定下来了
from PIL import Image
i = Image.open('./aa.png')
code_img_name = './code.png'
# crop根据指定区域进行图片裁剪
frame = i.crop(rangle)
frame.save(code_img_name)
# # 将验证码图片提交给超级鹰
chaojiying = Chaojiying_Client('yangmoumie', 'yangmou666.*', '908006')
im = open('code.png', 'rb').read()
print (chaojiying.PostPic(im, 9004)['pic_str'])
result = chaojiying.PostPic(im, 9004)['pic_str']
all_list = []   #要存储即将被点击的点的坐标[[x1,y1],[x2,y2]]
if '|' in result:
    list_1 = result.split("|")
    count_1 = len(list_1)
    for i in range(count_1):
        xy_list = []
        x = int(list_1[i].split(',')[0])
        y = int(list_1[i].split(',')[1])
        xy_list.append(x)
        xy_list.append(y)
        all_list.append(xy_list)
else:
    x = int(result.split(',')[0])
    y = int(result.split(',')[1])
    xy_list = []
    xy_list.append(x)
    xy_list.append(y)
    all_list.append(xy_list)
print(all_list)
# 遍历列表，使用动作链对每一个列表元素的x，y指定的位置进行点击操作
from selenium.webdriver import ActionChains
for l in all_list:
    x = l[0]
    y = l[1]
    # 切换参照物（也就是切换到验证码标签的位置）
    ActionChains(bro).move_to_element_with_offset(code_img_ele,x,y).click().perform()
    time.sleep(0.5)


bro.find_element_by_id('J-login').click()
# time.sleep(5)
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
wait = WebDriverWait(bro, 10)
fangkuai = wait.until(EC.element_to_be_clickable((By.ID, "nc_1_n1z")))
# fangkuai = bro.find_element_by_id('nc_1_n1z')
action = ActionChains(bro)
action.click_and_hold(fangkuai)
action.move_by_offset(xoffset=300,yoffset=0)
action.pause(1).release().perform()
bro.implicitly_wait(10)
time.sleep(5)
bro.quit()